package com.wuliu.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.wuliu.common.utils.StringUtils;
import com.wuliu.system.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.dromara.x.file.storage.core.upload.UploadPretreatment;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.stream.Stream;

/**
 * 文档地址：<a href="https://spring-file-storage.xuyanwu.cn/#/">...</a>
 *
 * @author realue
 * @version 1.0
 * @date 2023-10-12 11:37
 */
@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Resource
    private FileStorageService fileStorageService;

    /**
     * 文件上传
     *
     * @param file     支持 File、MultipartFile、byte[]、InputStream、URL、URI、String
     * @param filePath
     * @return URL
     * @author realue
     */
    @Override
    public String uploadFile(Object file, String filePath) {
        DateTime dateTime = new DateTime();
        UploadPretreatment uploadPretreatment = fileStorageService.of(file);
        if (StringUtils.isNotEmpty(filePath)) {
            if (!filePath.endsWith("/")) {
                filePath = filePath + "/";
            }
            filePath = filePath + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/";
            uploadPretreatment.setPath(filePath);
        }
        //InputStream、URL、URI、String,byte[] 等方式上传，暂时无法获取 originalFilename 属性，最好手动设置
        if (file instanceof InputStream || file instanceof URL || file instanceof URI ||
                file instanceof String || file instanceof byte[]) {
            String fileName = IdUtil.getSnowflakeNextIdStr() + ".png";
            uploadPretreatment.setOriginalFilename(fileName);
        }
        FileInfo fileInfo = uploadPretreatment.upload();
        return fileInfo.getUrl();
    }

    /**
     * 批量上传文件
     *
     * @param files
     * @param filePath
     * @return
     */
    @Override
    public String[] uploadFiles(Object[] files, String filePath) {
        return Arrays.stream(files).map(t -> uploadFile(t, filePath)).toArray(String[]::new);
    }
}
